import React, { useEffect, useState } from 'react';
import { history, connect } from 'umi';
import { Card, Button, Checkbox, Space } from 'antd';
import TableDataBlock from '@/components/TableDataBlock';
import StageConfigurationSetting from '@/components/StageConfigurationSetting'
import { field_data } from '@/common/contact'
import './index.less'
function arraysHaveSameElements(arr1, arr2) {
    // 如果数组长度不同，直接返回false
    if (arr1.length !== arr2.length) return false;

    // 使用Map来记录每个元素的出现次数
    const countMap1 = new Map();
    const countMap2 = new Map();

    // 统计第一个数组的元素频率
    for (const item of arr1) {
        // 使用类型+值作为键，以区分不同类型但值相同的元素
        const key = typeof item + '|' + item;
        countMap1.set(key, (countMap1.get(key) || 0) + 1);
    }

    // 统计第二个数组的元素频率
    for (const item of arr2) {
        const key = typeof item + '|' + item;
        countMap2.set(key, (countMap2.get(key) || 0) + 1);
    }

    // 如果两个Map的大小不同，说明有不同元素
    if (countMap1.size !== countMap2.size) return false;

    // 检查每个元素的计数是否相同
    for (const [key, count] of countMap1) {
        if (countMap2.get(key) !== count) return false;
    }

    return true;
}
function findStageConfig(organizationStageConfigMainList, stageIdentification, stageType) {
    // 遍历主阶段列表
    for (const mainStage of organizationStageConfigMainList) {
        // 检查主阶段是否匹配
        if (mainStage.stageIdentification === stageIdentification) {
            // 如果主阶段有对应的stageType配置，直接返回
            if (mainStage.organizationStageConfigStageTypeList && mainStage.organizationStageConfigStageTypeList.length > 0) {
                const stageTypeConfig = mainStage.organizationStageConfigStageTypeList.find(
                    config => config.stageType === stageType
                );
                if (stageTypeConfig) {
                    return stageTypeConfig;
                }
            }
            // 如果没有找到，继续检查子阶段
            break;
        }

        // 检查子阶段
        if (mainStage.organizationStageConfigSubStageList && mainStage.organizationStageConfigSubStageList.length > 0) {
            for (const subStage of mainStage.organizationStageConfigSubStageList) {
                if (subStage.stageIdentification === stageIdentification) {
                    // 在子阶段中查找匹配的stageType配置
                    if (subStage.organizationStageConfigStageTypeList && subStage.organizationStageConfigStageTypeList.length > 0) {
                        const stageTypeConfig = subStage.organizationStageConfigStageTypeList.find(
                            config => config.stageType === stageType
                        );
                        if (stageTypeConfig) {
                            return stageTypeConfig;
                        }
                    }
                    break;
                }
            }
        }
    }

    // 如果没有找到匹配的配置，返回null或undefined
    return null;
}
const RenderComponents = (props) => {
    const { data, index } = props
    const {
        renderType
    } = data
    if (renderType === 'list') {
        const { list = [], title, conditionType = 'all', amount } = data
        return <Space direction='vertical'>
            {list.map(val => {
                const { label, finshFlag } = val
                return <Space>
                    <Checkbox disabled={true} checked={finshFlag === '1'}>{finshFlag === '1' ? label : ''}</Checkbox>
                    {finshFlag !== '1' ? label : ''}
                </Space>
            })}
        </Space>
    }
    else if (renderType === 'date') {
        const { list = [], title, conditionType = 'all', amount, dayLess, finishExpectedRegistrationDateFlag
        } = data
        return <Space>
            <Checkbox disabled={true} checked={finishExpectedRegistrationDateFlag === '1'}>{finishExpectedRegistrationDateFlag === '1' ? `小于${dayLess}天` : ''}</Checkbox>
            {finishExpectedRegistrationDateFlag !== '1' ? `小于${dayLess}天` : ''}
        </Space>
    }
    else if (renderType === 'score') {
        const { list = [], title, conditionType = 'all', amount, intention, finishIntentionFlag
        } = data
        return <Space>
            <Checkbox disabled={true} checked={finishIntentionFlag === '1'}>{finishIntentionFlag === '1' ? `意向度${intention}` : ""}</Checkbox>
            {finishIntentionFlag !== '1' ? `意向度${intention}` : ""}
        </Space>
    }
    else if (renderType === 'order') {
        const { list = [], title, conditionType = 'all', amount, intention, money, finishAmountFlag, finishMoneyFlag
        } = data
        return <Space direction='vertical'>
            <Space>
                <Checkbox disabled={true} checked={finishAmountFlag === '1'}>{finishAmountFlag === '1' ? `订单数量${amount}` : ''}</Checkbox>
                {finishAmountFlag !== '1' ? `订单数量${amount}` : ''}
            </Space>
            <Space>
                <Checkbox disabled={true} checked={finishMoneyFlag === '1'}>  {finishMoneyFlag === '1' ? `订单金额${money}` : ''}</Checkbox>
                {finishMoneyFlag !== '1' ? `订单金额${money}` : ''}
            </Space>

        </Space>
    }
    else if (renderType === 'field') {

        const { list = [], title, conditionType = 'all', amount, intention, money, fields = []
        } = data

        return <Space direction='vertical'>
            {list.map(val => {
                const { label, finshFlag } = val
                return <Space>
                    <Checkbox disabled={true} checked={finshFlag === '1'}>{finshFlag === '1' ? field_data[label] : ''}</Checkbox>
                    {finshFlag !== '1' ? field_data[label] : ''}
                </Space>
            })}
        </Space>
    }
}
const TableRender = (props) => {
    const { data } = props
    const [list, setList] = useState([])

    const [userData, setUserData] = useState({ scoreCondition: {}, scoreRelation: null })
    useEffect(() => {
        if (!data) {
            setList([])
            setUserData({
                scoreCondition: {}, scoreRelation: null
            })
        } else {
            const { organizationStageConfig = {}
            } = data
            const {
                collectConditionList = [],
                expectedRegistrationDateConditionList = [],
                followUpStatusConditionList = [],
                intentionConditionList = [],
                intentionCoursesConditionList = [],
                intentionDirectionConditionList = [],
                materialConditionList = [],
                orderConditionList = [],
                scoreCondition = {},
                scoreRelation,
                tagGroupConditionList = [],
                thirdEventConditionList = [],
                thirdEventGroupConditionList = [],
                userFieldConditionList = [],
                userTagConditionList = [],
                materialCategoryConditionList = []
            } = organizationStageConfig
            const initList = [
                ...collectConditionList.map(val => {
                    const {
                        stageConfigCollectList = [],
                        finishCollectList = []
                    } = val
                    return {
                        ...val,
                        title: '表单条件',
                        renderType: 'list',
                        list: stageConfigCollectList.map(c => {
                            return {
                                label: c.collectTitle,
                                id: c.id,
                                finshFlag: finishCollectList.find(c.id) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...expectedRegistrationDateConditionList.map(val => {
                    return {
                        ...val,
                        renderType: 'date',
                        title: '报名时间'
                    }
                }),
                ...followUpStatusConditionList.map(val => {
                    const {
                        stageConfigFollowUpStatusList = [],
                        finishFollowUpStatusList = []
                    } = val
                    return {
                        ...val,
                        title: '跟进状态',
                        renderType: 'list',
                        list: stageConfigFollowUpStatusList.map(c => {
                            return {
                                label: c.followUpStatus,
                                id: c.id,
                                finshFlag: finishFollowUpStatusList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...intentionConditionList.map(val => {
                    return {
                        ...val,
                        title: '意向度',
                        renderType: 'score',
                    }
                }),
                ...intentionCoursesConditionList.map(val => {
                    const { stageConfigIntentionCourseList = [],
                        finishIntentionCoursesList = []
                    } = val
                    return {
                        ...val,
                        title: '意向课程',
                        renderType: 'list',
                        list: stageConfigIntentionCourseList.map(val => {
                            return {
                                label: val.courseName,
                                id: val.id,
                                finshFlag: finishIntentionCoursesList.find((e) => { return val.id === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...intentionDirectionConditionList.map(val => {
                    const { stageConfigIntentionDirectionList = [], finishIntentionDirectionsList } = val
                    return {
                        ...val,
                        title: '意向方向',
                        renderType: 'list',
                        list: stageConfigIntentionDirectionList.map(c => {
                            return {
                                label: c.intentionDirection,
                                id: c.id,
                                finshFlag: finishIntentionDirectionsList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...materialConditionList.map(val => {
                    const { stageConfigMaterialList = [], finishMaterialList = [] } = val
                    return {
                        ...val,
                        title: '素材',
                        renderType: 'list',
                        list: stageConfigMaterialList.map(c => {
                            return {
                                label: c.materialName,
                                id: c.id,
                                finshFlag: finishMaterialList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...materialCategoryConditionList.map(val => {
                    const { materialCategoryList = [], finishMaterialCategoryList = [] } = val
                    return {
                        ...val,
                        title: '素材分类',
                        renderType: 'list',
                        list: materialCategoryList.map(c => {
                            return {
                                label: c.categoryName,
                                id: c.id,
                                finshFlag: finishMaterialCategoryList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...orderConditionList.map(val => {
                    return {
                        ...val,
                        title: '订单',
                        renderType: 'order',
                    }
                }),
                ...tagGroupConditionList.map(val => {
                    const { tagGroupList = [], finishTagGroupList = [] } = val
                    return {
                        ...val,
                        title: '标签组',
                        renderType: 'list',
                        list: tagGroupList.map(c => {
                            return {
                                label: c.groupName,
                                id: c.id,
                                finshFlag: finishTagGroupList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...thirdEventConditionList.map(val => {
                    const { stageConfigThirdEventList = [], finishThirdEventList = [] } = val
                    return {
                        ...val,
                        title: '三方事件',
                        renderType: 'list',
                        list: stageConfigThirdEventList.map(c => {
                            return {
                                label: c.eventName,
                                id: c.key,
                                finshFlag: finishThirdEventList.find((e) => { return c.eventKey === e }) ? '1' : '0'
                            }
                        })
                    }
                }),
                ...thirdEventGroupConditionList.map(val => {
                    const { thirdEventGroupList = [], finishThirdEventGroupList = [] } = val
                    return {
                        ...val,
                        title: '三方组',
                        renderType: 'list',
                        list: thirdEventGroupList.map(c => {
                            return {
                                label: c.tagName,
                                id: c.id,
                                finshFlag: finishThirdEventGroupList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        }),
                    }
                }),
                ...userFieldConditionList.map(val => {
                    const { fields = '', finishFieldList = [] } = val
                    const newList = fields.split(',').filter(val => { return val })
                    return {
                        ...val,
                        title: '客户',
                        renderType: 'field',
                        fields: newList,
                        list: newList.map(c => {
                            return {
                                label: c,
                                id: c,
                                finshFlag: finishFieldList.find((e) => { return c === e }) ? '1' : '0'
                            }
                        }),
                        finshFlag: arraysHaveSameElements(newList, finishFieldList)
                    }
                }),
                ...userTagConditionList.map(val => {
                    const { stageConfigTagList = [], finishTagList = [] } = val
                    return {
                        ...val,
                        title: '标签',
                        renderType: 'list',
                        list: stageConfigTagList.map(c => {
                            return {
                                label: c.tagName,
                                id: c.id,
                                finshFlag: finishTagList.find((e) => { return c.id === e }) ? '1' : '0'
                            }
                        }),
                    }
                })
            ]
            setUserData({
                scoreCondition,
                scoreRelation
            })
            setList(initList)
        }
    }, [data])
    const getColumns = [

        {
            title: '其他条件',
            width: 200,
            dataIndex: 'title',
            render: (e, record) => {
                const { adminFinishFlag } = record
                return <Space>
                    <Checkbox disabled={true} checked={adminFinishFlag === '1'}>{adminFinishFlag === '1' ? e : ''}</Checkbox>
                    {adminFinishFlag !== '1' ? e : ''}
                </Space>
            }
        },
        {
            title: '限制',
            width: 200,
            dataIndex: 'conditionType',
            render: (e) => {
                return {
                    all: '全部',
                    any: '任意 '
                }[e]
            }
        },
        {
            title: '事件小项',
            dataIndex: 'lockFlag',
            render: (e, record) => {
                return <RenderComponents data={record}></RenderComponents>
            }
        },


    ]
    const { scoreCondition = {}, scoreRelation } = userData
    const { score,
        finishScore
    } = scoreCondition
    return <div>
        <div className='Standard_tableRender_box'>
            <div className='Standard_tableRender_warning'>
            </div>
            <div>
                {scoreRelation === '1' ? <div>
                    满足得分条件<span className='Standard_tableRender_label'>或</span>其他条件两类才可达标客户
                </div> : <div>
                    满足得分条件<span className='Standard_tableRender_label'>和</span>其他条件两类才可达标客户
                </div>}

            </div>
        </div>
        <div className='Standard_header_title'>得分条件</div>
        <div className='Standard_header_body'>
            <div className='Standard_header_left'>所需积分</div>
            <div className=''>{!finishScore && finishScore !== 0 ? '--' : finishScore}/{!score && score !== 0 ? '--' : score}</div>
        </div>
        <div style={{ marginTop: 24 }} className='Standard_header_title'>其他条件</div>
        <div className=''>
            <TableDataBlock
                noCard={false}
                columns={getColumns}
                list={list}
                pagination={false}></TableDataBlock>
        </div>
    </div >
}
const Standard = (props) => {
    const { loading, dispatch, id } = props
    const [active, setActive] = useState(null)
    const [cardActive, setCardActive] = useState('admin')
    const [list, setList] = useState([])
    const [data, setData] = useState([])
    useEffect(() => {
        fetchList()
        fetchData()
    }, [])
    const selectList = [
        { tab: '达标条件', key: 'admin' },
        { tab: '客户流转条件', key: 'auto' },
    ]
    const fetchList = () => {
        dispatch({
            type: 'user/fetchListStageInfoBase',
            callback: (e) => {
                const { stageInfoList } = e
                setList(stageInfoList.reduce((item, val) => {
                    const { subStageInfoList = [], stageInfo } = val
                    return [...item, {
                        ...val,
                        ...stageInfo,
                    }, ...subStageInfoList.map(c => {
                        return { ...c, stageInfo: c }
                    })]
                }, []))
                // setData(s)
            }
        })

    }
    const fetchData = (props) => {
        dispatch({
            type: 'behaviorEecord/fetchOrganizationStageConfig',
            payload: {
                queryFor: 'withFinish',
                organizationUserId: id
            },
            callback: (e = [], s = []) => {
                setData(s)
            }
        })
    }
    const renderDataAuto = findStageConfig(data, active, 'auto')
    const renderDatayg = findStageConfig(data, active, 'admin')

    console.log(renderDataAuto, renderDatayg, '---------123----')
    return <Card
        className='Standard_box'
        tabList={selectList}
        activeTabKey={cardActive}
        // extra={<Button className='Standard_btn'>异议</Button>}
        onTabChange={(key) => {
            setCardActive(key);
        }}
        bordered={false}>
        <StageConfigurationSetting NoCard={true} hideCard={false} data={list} onChange={(e) => {
            setActive(e)
        }}></StageConfigurationSetting>
        <TableRender data={cardActive !== 'auto' ? renderDatayg : renderDataAuto}></TableRender>
    </Card>
}
export default connect(({ subscriber, loading }) => ({
    loading: loading.effects['behaviorEecord/fetchOrganizationStageConfig'],
}))(Standard);
